package com.voc.cpnc;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.util.SparseArray;
import android.widget.TextView;


import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.voc.cpnc.hook_alipay.AliPayHook;
import com.voc.cpnc.utils.JsonUtils;
import com.voc.cpnc.utils.LogUtils;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;

import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XC_MethodReplacement;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage;

public class MainXPosed implements IXposedHookLoadPackage {

    private static final String RECEIVER_ACTION_NMB_GET_WX_OPENID = "com.voc.cpnc.ACTION_NMB_GET_WX_OPENID";
    private static final String RECEIVER_ACTION_NMB_SEND_WX_OPENID = "com.voc.cpnc.ACTION_NMB_SEND_WX_OPENID";


    private Context mContext;

    @Override
    public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpparam) throws Throwable {
        final String packageName = lpparam.processName;

//        //Hook 支付宝
//        if (packageName.equals(Constants.ALI_PAY_PACKAGE)) {
//            AliPayHook hook = new AliPayHook(lpparam);
//            hook.hookMainActivity();
//        }

        if (packageName.equals("com.taobao.taobao")) {

            XposedHelpers.findAndHookMethod(Activity.class, "onCreate", Bundle.class, new XC_MethodHook() {
                @Override
                protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                    super.afterHookedMethod(param);
                    LogUtils.e("Activity onCreate：" + param.getClass().getName());
                    XposedBridge.log("Activity onCreate：" + param.getClass().getName());
                }
            });

            Class<?> chatMessage = XposedHelpers.findClassIfExists("com.taobao.taolive.sdk.model.message.ChatMessage", lpparam.classLoader);
            XposedHelpers.findAndHookMethod("tb.jzy$b", lpparam.classLoader, "b", chatMessage, new XC_MethodHook() {
                @Override
                protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                    super.beforeHookedMethod(param);
                    LogUtils.e("========b方法 chatMessage=======" + JsonUtils.objectToString(param.args[0]));
                }
            });

            XposedHelpers.findAndHookMethod("com.taobao.taolive.room.ui.view.TopMessageView", lpparam.classLoader, "setText", String.class, new XC_MethodHook() {
                @Override
                protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                    super.beforeHookedMethod(param);
                    LogUtils.e("========setText方法 String=======" + JsonUtils.objectToString(param.args[0]));
                }
            });

        }


        /**
         * HOOK抖音直播用户流量数据
         * 抖音版本：11.3.0
         * */
        if (packageName.equals("com.ss.android.ugc.aweme")) {

            //Activity信息
            XposedHelpers.findAndHookMethod(Activity.class, "onCreate", Bundle.class, new XC_MethodHook() {
                @Override
                protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                    super.afterHookedMethod(param);
                    LogUtils.e("Activity onCreate：".concat(param.thisObject.getClass().toString()));
                }
            });

            //获取用户浏览数据（只要用户进入直播间则视为潜在客户）
            //钩住适配器onBindViewHolder(xx,xx)方法
            Class<?> viewHolder = XposedHelpers.findClassIfExists("android.support.v7.widget.RecyclerView$ViewHolder", lpparam.classLoader);
            XposedHelpers.findAndHookMethod("com.bytedance.android.livesdk.chatroom.ui.fe", lpparam.classLoader, "onBindViewHolder", viewHolder, int.class, new XC_MethodHook() {
                @Override
                protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                    super.beforeHookedMethod(param);
                    //获取全局List集合变量,从而遍历
                    List<Object> objectList = (List<Object>) XposedHelpers.getObjectField(param.thisObject, "c");
                    Object object = objectList.get((Integer) param.args[0]);
                    //通过广播移交主体APP发至服务解析（不建议直接发至服务解析）
                    LogUtils.e("用户具体数据信息：".concat(JsonUtils.objectToString(object)));
                }
            });

            //获取直播榜单的用户数据（高质量用户，抖音默认只展示100位用户信息）
            //可设置定时获取，榜单数据会有变化，对比

            //自动向用户发送私信（陌生人最大发送3条信息），并关注高质量用户
            //s

            //下载原视频（不带水印）
            //亦可看作播放量（因为每下载一次原视频，播放量将自动+1）

        }

        if (packageName.equals("com.xunyaosoft.zcnos")) {

            //Activity信息
            XposedHelpers.findAndHookMethod(Activity.class, "onCreate", Bundle.class, new XC_MethodHook() {
                @Override
                protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                    super.afterHookedMethod(param);
                    mContext = (Context) param.thisObject;
                    LogUtils.e("Activity onCreate：".concat(param.thisObject.getClass().toString()));

                    hook(param.thisObject.getClass().getClassLoader());
                    if (param.thisObject.getClass().getName().equals("com.xunyaosoft.zcnos.MainActivity")) {
                        NMBBroadcastReceiver receiver = new NMBBroadcastReceiver();
                        IntentFilter intentFilter = new IntentFilter();
                        intentFilter.addAction(RECEIVER_ACTION_NMB_GET_WX_OPENID);
                        (mContext).registerReceiver(receiver, intentFilter);
                        LogUtils.e("cn.com.cmbc.newmbank.activity.MainActivity 注册广播");

//                        XposedHelpers.callMethod(param.thisObject, "setLocalString", new Class[]{String.class, String.class}, "deviceId", "sokuuec6zxda5v6r");
                    }

                }
            });

        }

    }

    private String deviceId;

    private void hook(ClassLoader classLoader) {

        XposedHelpers.findAndHookMethod("com.xunyaosoft.zcnos.wxapi.WXEntryActivity", classLoader, "bindWxAcct", String.class, new XC_MethodReplacement() {
            @Override
            protected Object replaceHookedMethod(MethodHookParam methodHookParam) throws Throwable {
                LogUtils.e("===bindWxAcct=======" + methodHookParam.args[0]);

                Intent intent = new Intent();
                intent.setAction(RECEIVER_ACTION_NMB_SEND_WX_OPENID);
                intent.putExtra("wxOpenid", methodHookParam.args[0].toString());
                intent.putExtra("deviceId", deviceId);
                mContext.sendBroadcast(intent);

                Activity activity = (Activity) methodHookParam.thisObject;
                activity.finish();
                return null;
            }
        });
//        XposedHelpers.findAndHookMethod("com.xunyaosoft.zcnos.wxapi.WXEntryActivity", classLoader, "bindWxAcct", String.class, new XC_MethodHook() {
//            @Override
//            protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
//                super.beforeHookedMethod(param);
//                LogUtils.e("===============================" + deviceId);
//                XposedHelpers.callMethod(param.thisObject, "setLocalString", new Class[]{String.class, String.class}, "deviceId", deviceId);
//
//                Intent intent = new Intent();
//                intent.setAction(RECEIVER_ACTION_NMB_SEND_WX_OPENID);
//                intent.putExtra("wxOpenid", param.args[0].toString());
//                mContext.sendBroadcast(intent);
//            }
//        });

    }

    /**
     * 广播监听
     */
    private class NMBBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction() == null)
                return;
            if (intent.getAction().equals(RECEIVER_ACTION_NMB_GET_WX_OPENID)) {

                LogUtils.e("接受到“获取微信openid”广播");
                deviceId = intent.getStringExtra("deviceId");

                IWXAPI api = WXAPIFactory.createWXAPI(mContext, "wxc9e72868c7e2f5cd");
                SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = String.valueOf(System.currentTimeMillis());
                boolean sendReq = api.sendReq(req);
                if (sendReq) {
                    LogUtils.e("拉起微信--成功");
                } else {
                    LogUtils.e("拉起微信--失败");
                }
            }
        }
    }
}
